import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/common/widges/appbar.dart';
import 'package:guochaoapp/common/widges/dialog.dart';
import 'package:guochaoapp/controller/mine/address_controller.dart';
import 'package:guochaoapp/model/address_entity.dart';
import 'package:guochaoapp/r.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';

class GCAddressPage extends StatefulWidget {
  @override
  _GCAddressPageState createState() => _GCAddressPageState();
}

class _GCAddressPageState extends State<GCAddressPage> {
  GCAddressController c = Get.put(GCAddressController());

  //分页请求page
  int page = 1;
  int size = 0;

  UserService userService = Get.find();
  List<AddressDataRecord> records = [];

  var isEmpty = true.obs;

  Future<void> onRefresh() async {
    await requestAddressList(false);
  }

  Future<void> onLoadMore() async {
    await requestAddressList(true);
  }

  deleteTap(int index) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (ctx) {
          return GCDialog(
            items: ['取消', '确认'],
            content: '确认删除该地址？',
            onTap: (_) {
              var model = records[index];

              HttpClient.request(
                  url: UserAddrApi.usersAddr,
                  method: Method.DELETE,
                  data: {
                    "isDefault": true,
                    "uid": userService.userInfo.uid,
                    "addrId": model.addrId,
                  },
                  onSuccess: (r, _) async {
                    setState(() {
                      records.removeAt(index);
                    });
                  },
                  onFailed: (err) async {});
            },
          );
        });
  }

  editTap(int index) {
    var model = records[index];

    Get.toNamed(Routes.ADDADDRESS, arguments: ["edit", model]);
  }

  addressAddTap() {
    Get.toNamed(Routes.ADDADDRESS, arguments: ["new"]);
  }

  requestAddressList([bool isloadMore = false]) async {
    log("requestAddressList__" + isloadMore.toString());
    if (isloadMore) {
      page++;
    } else {
      page = 1;
    }

    await HttpClient.request<AddressEntity>(
        url: UserAddrApi.usersAddr,
        method: Method.GET,
        params: {"uid": userService.userInfo.uid, "current":page, "size": 5},
        onSuccess: (_, model) async{
          Future.delayed(Duration(milliseconds: 1000)).then((e) {
            setState(() {
              if(model.data.records.length == 0) {
                if(isloadMore) {
                  c.er_controller.finishRefresh(noMore: true);
                } else {
                  isEmpty.value = true;
                  records = model.data.records;
                  c.er_controller.finishRefresh();
                  c.er_controller.resetLoadState();
                }
              } else {
                if (isloadMore) {
                  records += model.data.records;
                  c.er_controller.finishLoad();
                } else {
                  records = model.data.records;
                  c.er_controller.finishRefresh();
                }
              }
            });
          });


        },
        onFailed: (err) async {
          page--;
          c.er_controller.finishRefresh();
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: GCAppBar(
          titleText: "收货地址列表",
          actions: [
            Row(
              children: [
                GestureDetector(
                    onTap: addressAddTap,
                    child: Image.asset(R.assetsIconAddressadd,
                        width: 20, height: 20)),
                SizedBox(width: 23)
              ],
            )
          ],
        ),
        body: _initSubviews());
  }

  _initSubviews() {
    return _recordListView();
  }

  _recordListView() {
    return EasyRefresh.custom(
      emptyWidget: records.length == 0 ? _noDataView() : null,
      firstRefresh: true,
      enableControlFinishLoad: true,
      enableControlFinishRefresh: true,
      controller: c.er_controller,
      header: BallPulseHeader(color: Theme.of(Get.context).primaryColor),
      footer: BallPulseFooter(color: Theme.of(Get.context).primaryColor),
      onRefresh: onRefresh,
      onLoad: onLoadMore,
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate((context, index) {
            return _recordItem(index);
          }, childCount: records.length),
        )
      ],
    );
  }

  _recordItem(int index) {
    AddressDataRecord model = records[index];
    return GestureDetector(
      onTap: () {
        _choose(model);
      },
      child: Container(
        padding: EdgeInsets.only(top: 10, left: 12, right: 17, bottom: 9),
        color: Colors.white,
        height: 69,
        child: Column(
          children: [
            Expanded(
                child: Container(
              child: Row(
                children: [
                  Column(children: [
                    Image.asset(
                      R.assetsIconHomeBarcket,
                      width: 20,
                      height: 20,
                    ),
                    Expanded(child: SizedBox()),
                  ]),
                  SizedBox(width: 15),
                  Expanded(
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(children: [
                            Text(model.receiverName,
                                style: TextStyle(
                                    color: Color(0xFF666666), fontSize: 14)),
                            SizedBox(width: 5),
                            Text(model.receiverPhone,
                                style: TextStyle(
                                    color: Color(0xFFA9A8A8), fontSize: 12)),
                          ]),
                          SizedBox(height: 3),
                          Stack(children: [
                            Image.asset(R.assetsIconHomeBarcket,
                                width: 8, height: 8),
                            Text("      " + model.receiverAddr,
                                style: TextStyle(
                                    color: Color(0xFFA9A8A8), fontSize: 8)),
                          ]),
                        ]),
                  ),
                  Container(
                    width: 95,
                    height: double.infinity,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        GestureDetector(
                          onTap: () {
                            deleteTap(index);
                          },
                          child: Container(
                              width: 47,
                              child: Center(
                                  child: Text(
                                "删除",
                                style: TextStyle(
                                    fontSize: 12, color: Color(0xFF666666)),
                              ))),
                        ),
                        Container(
                            child: Column(children: [
                              SizedBox(height: 10),
                              Expanded(
                                  child: Container(color: Color(0xFFA9A8A8))),
                              SizedBox(height: 10),
                            ]),
                            height: double.infinity,
                            width: 1),
                        GestureDetector(
                          onTap: () {
                            editTap(index);
                          },
                          child: Container(
                              width: 47,
                              child: Center(
                                  child: Text("编辑",
                                      style: TextStyle(
                                          fontSize: 12,
                                          color: Color(0xFF666666))))),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            )),
            Container(height: 1, color: Color(0xFFF4F8FE)),
          ],
        ),
      ),
    );
  }

  _noDataView() {
    return Container(
        width: ScreenUtil().screenWidth,
        height: ScreenUtil().screenHeight,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              R.assetsIconNoaddress,
              width: 154,
              height: 154,
            ),
            SizedBox(height: 10),
            Text("这里还没有收货地址！",
                style: TextStyle(color: Color(0xFF999999), fontSize: 14))
          ],
        ));
  }

  _choose(AddressDataRecord model) {
   Get.back(result: model);
  }
}
